#pragma once
#include "Common.h"
#include"ThreadCache.h"
#include "PageCache.h"
#include "ObjectPool.h"
std::mutex _mtx;
void* ConcurrentAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		size_t alignSize = SizeClass::RoundUp(size);
		size_t kpage = alignSize >> PAGE_SHIFT;
		PageCache::GetInstance()->_pagemtx.lock();
		Span* span = PageCache::GetInstance()->NewSpan(alignSize);
		span->_objSize = alignSize;
		PageCache::GetInstance()->_pagemtx.unlock();
		
		void* ret = (void*)(span->_pageId << PAGE_SHIFT);
		return ret;
	}
	else
	{
		if (pTLSThreadCache == nullptr)
		{
			_mtx.lock();
			static ObjectPool<ThreadCache>  _tcPool;
			pTLSThreadCache = _tcPool.New();
			_mtx.unlock();
		}
		return pTLSThreadCache->Allocate(size);
	}
}

void ConcurrentFree(void* ptr)
{
	assert(pTLSThreadCache);
	Span* span = PageCache::GetInstance()->MapObjectToSpan(ptr);
	size_t size = span->_objSize;
	if (size > MAX_BYTES)
	{
		PageCache::GetInstance()->_pagemtx.lock();
		PageCache::GetInstance()->ReleaseSpanToPageCache(span);
		PageCache::GetInstance()->_pagemtx.unlock();

		return;
	}

	pTLSThreadCache->Deallocate(ptr, size);
}

